<template>
  <teleport to="html">
    <div
      class="getScroll"
      v-show="toTop"
      @click="scrollTop"
      :style="
        {
          position: props.position,
          top: props.top,
          left: props.left,
          right: props.right,
          bottom: props.bottom,
          width: props.width,
          height: props.height
        } as StyleValue
      "
    >
      <el-icon class="icon" :size="props.icon.iconSize" :color="props.icon.iconColor">
        <component :is="props.icon.iconName" />
      </el-icon>
    </div>
  </teleport>
</template>

<script setup lang="ts">
import { onActivated, onDeactivated, onMounted, onUnmounted, ref, type StyleValue } from "vue"

import type { IGetScrollInfo } from "./type"

const props = withDefaults(defineProps<IGetScrollInfo>(), {
  // element: () => window,
  position: "fixed",
  top: "",
  left: "",
  width: "16px",
  height: "16px",
  right: "100px",
  bottom: "50px",
  scrollTop: 0,
  visibilityBtnHeight: 510,
  icon: () => ({
    iconName: "ArrowUp",
    iconColor: "#999",
    iconSize: "20px"
  })
})

// 展示返回顶部按钮
const toTop = ref(false)

function scrollTop() {
  /*
    window.scrollTo() 方法将页面滚动到顶部位置，
    behavior: 'smooth' 属性使滚动动画平滑过渡。
  */
  window.scrollTo({
    top: props.scrollTop,
    behavior: "smooth"
  })
}

// 监听页面滚动事件的回调
function handleScroll() {
  // console.log(window.scrollY);
  // 屏幕滚动大小大于510 返回顶部按钮显示
  toTop.value = window.scrollY > props.visibilityBtnHeight
}

onMounted(() => {
  // 监听页面滚动事件
  window.addEventListener("scroll", handleScroll)
})

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll) // 释放
})
</script>

<style lang="less" scoped>
.getScroll {
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  padding: 20px;
  // font-size: 20px;
  font-weight: 600;
  border-radius: 50%;
  transition: all 0.8s;
  // color: #999;
  background-color: rgba(153, 153, 153, 0.2);
  z-index: 100;
  &:hover {
    color: #888;
    background-color: rgba(153, 153, 153, 0.4);
  }
}
</style>
